var utils = {
    phoneRegExp: /^1\d{10}$/, //手机号正则
    usernameRegExp: /^[a-zA-Z]\w{5,19}$/, //用户名正则
    companynameRegExp: /^[\u2E80-\u9FFF\（\）()]{2,46}$/, //公司名正则
    passwordRegExp: /^(?![0-9]+$)(?![a-zA-Z]+$)(?!([^(0-9a-zA-Z)]|[`~!@#$%^*()_+?:{},.\/;[\]])+$)([^(0-9a-zA-Z)]|[`~!@#$%^*()_+?:{},.\/;[\]]|[a-zA-Z]|[0-9]){8,}$/, //密码正则
    twoZuheRegExp: /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[`~!@#$%^*()_+?:{},.\/;[\]])+$)([^(0-9a-zA-Z)]|[`~!@#$%^*()_+?:{},.\/;[\]]|[a-z]|[A-Z]|[0-9]){8,}$/, //两两组合
    threeZuheRegExp: /^(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)(?=.*[`~!@#$%^*()_+?:{},.\/;[\]].*))[`~!@#$%^*()_+?:{},.\/;[\]0-9A-Za-z]{8,}$/, //三种组合密码正则
    emptyRegExp: /\S/, //为空正则
    numberRegExp: /^[0-9]*$/, //数字正则
    englishRegExp: /^[a-zA-Z]+$/, //字母正则
    fuhaoRegExp: /^[`~!@#$%^*()_+?:{},.\/;[\]]+$/, //符号正则
    phoneNameRegExp: /^[\u4E00-\u9FFF]{1,20}$/, //联系人正则
    aesKey: "O2BEeIv399qHQNhD6aGW8R8DEj4bqHXm", //aes加密key
    captchaAppId: "2001970626", //腾讯行为验证appid
    //地区处理
    Citymake: function(province, city) {
        var Cityname
        if (province == '北京市' || province == '上海市' || province == '天津市' || province == '重庆市' || province == '台湾省' || province == '香港特别行政区' || province == '澳门特别行政区' || province == '广西壮族自治区' || province == '西藏自治区' || province == '宁夏回族自治区' || province == '新疆维吾尔自治区') {
            Cityname = province.substr(0, 2)
        } else if (province == '内蒙古自治区') {
            Cityname = province.substr(0, 3)
        } else {
            Cityname = province.slice(0, -1) + '&nbsp;' + city.slice(0, -1)
        }
        return Cityname
    },
    // 价格处理
    Pricemake: function(price) {
        var Newprice
        if (parseInt(price) < 100000) {
            Newprice = Math.floor(price * 100) / 100
        } else {
            Newprice = Math.floor(price / 100) / 100 + '万'
        }
        return Newprice
    },
    //获取hostName
    getHostName: function() {
        var hostname = "";
        switch (window.location.hostname) {
            case "www.51caigou.com":
                hostname = "gateway.51caigou.com";
                break;
            case "testwww.51caigou.com":
                hostname = "testgateway.51caigou.com";
                break;
            case "testbwww.51caigou.com":
                hostname = "testbgateway.51caigou.com";
                break;
            case "testcwww.51caigou.com":
                hostname = "testcgateway.51caigou.com";
                break;
            default:
                hostname = "devgateway.51caigou.com";
        }
        return hostname;
    },

    //获取商家后台hostName
    getUserHostName: function() {
        var hostname = "";
        switch (window.location.hostname) {
            case "www.51caigou.com":
                hostname = "user.51caigou.com";
                break;
            case "testwww.51caigou.com":
                hostname = "testuser.51caigou.com";
                break;
            case "testbwww.51caigou.com":
                hostname = "testbuser.51caigou.com";
                break;
            case "testcwww.51caigou.com":
                hostname = "testcuser.51caigou.com";
                break;
            case "devwww.51caigou.com":
                hostname = "devuser.51caigou.com";
                break;
            default:
                hostname = "127.0.0.1:5501";
        }
        return hostname;
    },
    // 获取scrm hostname
    getscrmHostName: function() {
        var hostname = "";
        switch (window.location.hostname) {
            case "www.51caigou.com":
                hostname = "scrm.51caigou.com";
                break;
            case "testwww.51caigou.com":
                hostname = "testscrm.51caigou.com";
                break;
            case "testbwww.51caigou.com":
                hostname = "testbscrm.51caigou.com";
                break;
            case "testcwww.51caigou.com":
                hostname = "testcscrm.51caigou.com";
                break;
            default:
                hostname = "devscrm.51caigou.com";
        }
        return hostname;
    },
    ajaxPost: function(url, data, successfn, errorfn, async) {
        var that = this;
        $.ajax({
            type: "POST", //请求类型
            url: "//" + this.getHostName() + "" + url, //请求的 URL地址
            dataType: "json", //返回的数据类型
            contentType: "application/json",
            async: async === false ? async : true, //同步、异步
            headers: {
                "Authorization": "Basic Y2FpZ291d2FuZ19tZW1iZXJjZW50ZXI6Y2FpZ291d2FuZ19tZW1iZXJjZW50ZXJfc2VjcmV0",
                "Blade-Front-Auth": $.cookie('qqt-access-token'),
                "memberId": $.cookie('member-base-info') ? JSON.parse($.cookie('member-base-info')).memberId : ''
            },
            data: (data ? JSON.stringify(data) : data),
            success: function(res) {
                //console.log(res)
                if (!res.code) { //如果没有返回结果没有code值 特殊情况 如登录接口
                    successfn(res);
                } else if (res.code == 200) {
                    successfn(res);
                } else if (res.code == 401) {
                    that.clearLoginCookie()
                } else {
                    errorfn(res)
                }

            },
            error: function(res) {
                console.log(res)
                errorfn(JSON.parse(res.responseText))

            },
        });
    },
    ajaxGet: function(url, data, successfn, errorfn, async) {
        var that = this;
        $.ajax({
            type: "GET", //请求类型
            url: "//" + this.getHostName() + "" + url, //请求的 URL地址
            dataType: "json", //返回的数据类型
            async: async === false ? async : true, //同步、异步
            headers: {
                "Authorization": "Basic Y2FpZ291d2FuZ19tZW1iZXJjZW50ZXI6Y2FpZ291d2FuZ19tZW1iZXJjZW50ZXJfc2VjcmV0",
                "Blade-Front-Auth": $.cookie('qqt-access-token'),
                "memberId": $.cookie('member-base-info') ? JSON.parse($.cookie('member-base-info')).memberId : ''
            },
            data: data,
            success: function(res) {
                //console.log(res)
                if (res.code == 200) {
                    successfn(res);
                } else if (res.code == 401) {
                    that.clearLoginCookie()
                } else {
                    errorfn(res)
                }

            },
            error: function(res) {
                console.log(res)
                if (res.status == 401) {
                    that.clearLoginCookie()
                } else {
                    errorfn(JSON.parse(res.responseText))
                }


            },
        });
    },
    ajaxPut: function(url, data, successfn, errorfn, async) {
        var that = this;
        $.ajax({
            type: "PUT", //请求类型
            url: "//" + this.getHostName() + "" + url, //请求的 URL地址
            dataType: "json", //返回的数据类型
            contentType: "application/json",
            async: async === false ? async : true, //同步、异步
            headers: {
                "Authorization": "Basic Y2FpZ291d2FuZ19tZW1iZXJjZW50ZXI6Y2FpZ291d2FuZ19tZW1iZXJjZW50ZXJfc2VjcmV0",
                "Blade-Front-Auth": $.cookie('qqt-access-token'),
                "memberId": $.cookie('member-base-info') ? JSON.parse($.cookie('member-base-info')).memberId : ''
            },
            data: (data ? JSON.stringify(data) : data),
            success: function(res) {
                //console.log(res)
                if (!res.code) { //如果没有返回结果没有code值 特殊情况 如登录接口
                    successfn(res);
                } else if (res.code == 200) {
                    successfn(res);
                } else if (res.code == 401) {
                    that.clearLoginCookie()
                } else {
                    errorfn(res)
                }

            },
            error: function(res) {
                console.log(res)
                errorfn(JSON.parse(res.responseText))

            },
        });
    },
    //转换时间 分
    formatTime: function(second, type) {
        var second = Math.floor(second);
        var result = "";
        if (type == "m:s") {
            result = (second / 60).toFixed(2);
        }
        return result;
    },

    //获取设备类型 ios  android
    getMobileType: function() {
        var ua = navigator.userAgent;
        var mobileType = "";
        if (ua.indexOf("Android") > -1 || ua.indexOf("Linux") > -1) {
            mobileType = "android";
        } else if (ua.indexOf("iPhone") > -1) {
            mobileType = "ios";
        } else if (ua.indexOf("Windows Phone") > -1) {
            mobileType = "Windows";
        }
        return mobileType;
    },

    //判断是PC还是移动
    getEquipment: function() {
        var is_mobi =
            navigator.userAgent
            .toLowerCase()
            .match(
                /(ipod|ipad|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|wince)/i
            ) != null;
        var equipment = "";
        if (is_mobi) {
            equipment = "mobile";
        } else {
            equipment = "PC";
        }
    },

    //判断是否在微信内
    isWechat: function() {
        return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
    },

    //截取字符串
    interceptStrings: function(str, num) {
        var newStr = str;
        if (str.length > num) {
            newStr = str.substr(0, num - 1) + "...";
        }
        return newStr;
    },

    //截取字符串
    interceptStrings2: function(str, num) {
        var newStr = str;
        if (!str) {
            newStr = ''
        } else if (str.length > num) {
            newStr = str.substr(0, num) + "...";
        }
        return newStr;
    },

    //对象转URL参数
    parseParam: function(data, isPrefix) {
        // var paramStr = "";
        // if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        //     paramStr += "&" + key + "=" + encodeURIComponent(param);
        // } else {
        //     $.each(param, function (i) {
        //         var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
        //         if (i == 0) {
        //             paramStr += '' + $.param(this, k);
        //             return false
        //         }
        //         paramStr += '&' + $.param(this, k);


        //     });
        // }
        // return paramStr.substr(1);

        var isPrefix = isPrefix ? isPrefix : false;
        var prefix = isPrefix ? '?' : '';
        var _result = []
        for (var key in data) {
            var value = data[key];
            // 去掉为空的参数
            // if (['', undefined, null].includes(value)) {
            //     continue
            // }
            if (value.constructor === Array) {
                value.forEach(function(_value) {
                    _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
                })
            } else {
                _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
            }
        }

        return _result.length ? prefix + _result.join('&') : ''

    },

    //转换时间格式
    formatterDate: function(num, type) {
        var str = num;
        if (num) {
            var now = new Date(num * 1000);
            var year = now.getFullYear();
            var month = now.getMonth() + 1;
            var date = now.getDate();
            var hour = now.getHours();
            var minute = now.getMinutes();
            var second = now.getSeconds();
            if (type == "date") {
                str = year + "/" + this.addZero(month) + "/" + this.addZero(date);
            } else {
                str =
                    year +
                    "/" +
                    this.addZero(month) +
                    "/" +
                    this.addZero(date) +
                    " " +
                    this.addZero(hour) +
                    ":" +
                    this.addZero(minute)

            }
        }
        return str;
    },
    //时间格式 两位
    addZero: function(m) {
        return m < 10 ? "0" + m : m;
    },

    getFormatDate: function() {
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
        var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
        var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
        var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
        var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
        return year + "/" + month + "/" + date + " " + hour + ":" + minute;
    },

    //获取URL参数
    getUrlParam: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg); // 匹配目标参数
        if (r != null) return unescape(r[2]);
        return ''; // 返回参数值

    },

    //获取URL中？后面的参数
    getUrlParams: function() {
        //自动获取地址栏链接带？以及后面的字符串
        var url = window.location.search;
        //定义一个空对象
        var obj = {};
        //如果字符串里面存在?
        if (url.indexOf("?") != -1) {
            //从url的索引1开始提取字符串
            var str = url.substring(1);
            //如果存在&符号，则再以&符号进行分割
            var arr = str.split("&");
            //遍历数组
            for (var i = 0; i < arr.length; i++) {
                // obj对象的属性名 = 属性值，unescape为解码字符串
                obj[arr[i].split("=")[0]] = unescape(arr[i].split("=")[1]);
            }
        }
        // console.log(obj);
        return obj;
    },
    getUrlParamsDecode: function() {
        //自动获取地址栏链接带？以及后面的字符串
        var url = window.location.search;
        //定义一个空对象
        var obj = {};
        //如果字符串里面存在?
        if (url.indexOf("?") != -1) {
            //从url的索引1开始提取字符串
            var str = url.substring(1);
            //如果存在&符号，则再以&符号进行分割
            var arr = str.split("&");
            //遍历数组
            for (var i = 0; i < arr.length; i++) {
                // obj对象的属性名 = 属性值，unescape为解码字符串
                obj[arr[i].split("=")[0]] = decodeURI(arr[i].split("=")[1]);
            }
        }
        // console.log(obj);
        return obj;
    },
    // 修改url参数
    changeURLArg: function(url, arg, arg_val) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            var tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
    },
    //毫秒级倒计时
    countDown: function(leftTime, timeEle, timeBox) {
        var that = this;
        var timer = setInterval(function() { //倒计时
            leftTime -= 103;
            if (leftTime <= 0) { //如果时间差小于等于0
                clearInterval(timer); //清除定时器
                timeBox.hide();
            } else {
                var mi = Math.floor(leftTime / (1000 * 60) % 60); //分
                var se = Math.floor(leftTime / 1000 % 60); //秒
                var ms = parseInt(leftTime % 1000 / 10); //毫秒
                //console.log(leftTime%1000/10)
                timeEle.html(that.twoStr(mi) + ":" + that.twoStr(se) + ":" + that.twoStr(ms));
            }
        }, 103);
    },
    twoStr: function(num) {
        return num < 10 ? '0' + num : num;
    },

    /**
     * aes 加密方法，同java：AesUtil.encryptToBase64(text, aesKey);
     */
    encryptAES: function(data, key) {
        var dataBytes = CryptoJS.enc.Utf8.parse(data);
        var keyBytes = CryptoJS.enc.Utf8.parse(key);
        var encrypted = CryptoJS.AES.encrypt(dataBytes, keyBytes, {
            iv: keyBytes,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    },

    /**
     * aes 解密方法，同java：AesUtil.decryptFormBase64ToString(encrypt, aesKey);
     */
    decryptAES: function(data, key) {
        var keyBytes = CryptoJS.enc.Utf8.parse(key);
        var decrypted = CryptoJS.AES.decrypt(data, keyBytes, {
            iv: keyBytes,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Utf8.stringify(decrypted);
    },
    //获取距离当前时间过了多久
    formatterDateNews: function(time) {
        var time = new Date(time).getTime()
        var now = new Date().getTime()
        var result
        var minute = 1000 * 60
        var hour = minute * 60
        var day = hour * 24
        var week = day * 7
        var month = day * 30
        var year = day * 365
            // 现在时间 减去 传入时间 得到差距时间
        var diffValue = now - time
            // 小于 0 直接返回
        if (diffValue < 0) {
            return
        }
        var yearC = diffValue / year
        var monthC = diffValue / month
        var weekC = diffValue / week
        var dayC = diffValue / day
        var hourC = diffValue / hour
        var minC = diffValue / minute
        switch (true) {
            case yearC >= 1:
                // 如果大于一年就显示具体日期
                result = '一年以前'
                break
            case monthC >= 1:
                result = '' + parseInt(monthC) + '月前'
                break
            case weekC >= 1:
                result = '' + parseInt(weekC) + '周前'
                break
            case dayC >= 1:
                result = '' + parseInt(dayC) + '天前'
                break
            case hourC >= 1:
                result = '' + parseInt(hourC) + '小时前'
                break
            case minC >= 0:
                result = '' + Math.ceil(hourC) + '分钟前'
                break
            default:
                console.log('其他')
        }
        return result
    },
    /* 计算文本域输入数量 */
    textareaLimiter: function($_this, limit, $_elem) {
        $_this.on("keyup focus", function() {
            setCount($(this)[0], $_elem);
        });

        function setCount(src, elem) {
            var chars = src.value.length;
            if (chars > limit) {
                src.value = src.value.substr(0, limit);
                chars = limit;
            }
            elem.html(chars + "/" + limit);
        }
        setCount($_this[0], $_elem);
    },

    /* 登录存入cookie */
    setLoginCookie: function(type, data, stayLogin) { //存入数据类型 存入数据 是否保持两周内登录
        var _domain = window.location.hostname.indexOf("51caigou.com") != -1 ? ".51caigou.com" : window.location.hostname;
        if (type == "login-info") {
            $.cookie('qqt-access-token', data.access_token, { expires: 1, path: '/', domain: _domain }); //domain: 'chuhoo.com'
            $.cookie('qqt-login-info', JSON.stringify({
                // access_token: data.access_token,
                phone: data.phone,
                user_id: data.user_id,
                user_name: data.user_name,
                // refresh_token: data.refresh_token

            }), { expires: 1, path: '/', domain: _domain });
            $.cookie('qqt-refresh-token', data.refresh_token, { expires: 14, path: '/', domain: _domain });
            if (stayLogin === true) {
                $.cookie('qqt-stayLogin', "true", { expires: 14, path: '/', domain: _domain });
            } else if (stayLogin === false) {
                //     alert(2)
                $.cookie('qqt-stayLogin', "", { expires: -1, path: '/', domain: _domain });
            }
        } else if (type == "member-info") {
            $.cookie("member-base-info", JSON.stringify(data), { expires: 1, path: '/', domain: _domain })
        }
        //  else if (type == 'company-info') {
        //     $.cookie("member-base-info", JSON.stringify(data), { expires: 1, path: '/', domain: _domain })
        // }
    },

    /* 退出登录 清除cookie */
    clearLoginCookie: function() {
        //  alert(888888)
        var _domain = window.location.hostname.indexOf("51caigou.com") != -1 ? ".51caigou.com" : window.location.hostname;
        $.cookie('qqt-access-token', '', { expires: -1, path: '/', domain: _domain }); //domain: 'chuhoo.com'
        $.cookie('qqt-login-info', '', { expires: -1, path: '/', domain: _domain });
        $.cookie('member-base-info', '', { expires: -1, path: '/', domain: _domain });
        $.cookie('qqt-refresh-token', '', { expires: -1, path: '/', domain: _domain });
        $.cookie('qqt-stayLogin', '', { expires: -1, path: '/', domain: _domain });
    },
    clearMemberCookie: function() {
        var _domain = window.location.hostname.indexOf("51caigou.com") != -1 ? ".51caigou.com" : window.location.hostname;
        $.cookie('member-base-info', '', { expires: -1, path: '/', domain: _domain });
    },
    setTracking: function() {
        var UrlParam = this.getUrlParams();
        var _domain = window.location.hostname.indexOf("51caigou.com") != -1 ? ".51caigou.com" : window.location.hostname;
        if (UrlParam) {
            var urlData = {
                "froms": UrlParam.from,
                "kwd": UrlParam.kwd ? UrlParam.kwd : UrlParam.word,
                "src": UrlParam.src,
                "pg": UrlParam.pg,
                "btn": UrlParam.btn
            }

            urlData.froms && !$.cookie('qqt-track-data') && $.cookie('qqt-track-data', JSON.stringify(urlData), { expires: 1, path: '/', domain: _domain });
        }

    },
    /* 投放追踪 */
    getTracking: function(data) {
        data || (data = {});
        var _domain = window.location.hostname.indexOf("51caigou.com") != -1 ? ".51caigou.com" : window.location.hostname;
        var UrlParam = this.getUrlParams();
        var urlData = {
                "froms": UrlParam.from,
                "kwd": UrlParam.kwd ? UrlParam.kwd : UrlParam.word,
                "src": UrlParam.src,
                "pg": UrlParam.pg,
                "btn": UrlParam.btn
            }
            //判断cookie是否存在投放数据
        if ($.cookie('qqt-track-data')) {
            $.extend(data, JSON.parse($.cookie('qqt-track-data')));
            data.kwd = data.kwd ? this.decodeKwd(data.kwd) : '';
            return data
        } else {
            return data
        }
    },
    decodeKwd: function(kwd, count) {
        if (!count) {
            count = 0
        }
        var chineseReg = /[\u4e00 - \u9fa5]/
        if (chineseReg.test(kwd) || kwd.indexOf('%') == -1 || count >= 5) {
            return kwd
        } else {
            count += 1
            kwd = decodeURI(kwd);
            return this.decodeKwd(kwd, count)
        }
    },
    /**
     * 生成uuid
     * @returns  //f0ed305c-ec19-4967-b323-eef07a4cf2d8
     */
    generateUUID: function() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }

};

export default utils

//文字横向滚动插件
$.fn.textScroll = function() {
    var p = $(this),
        c = p.children(),
        speed = 5000; //值越大速度越小
    var cw = c.width(),
        pw = p.width();
    var t = (cw / 100) * speed;
    var f = null,
        t1 = 0;

    function ani(tm) {
        counttime();
        console.log(-cw)
        c.animate({ left: -cw }, tm, "linear", function() {
            c.css({ left: "50px" });
            clearInterval(f);
            t1 = 0;
            t = ((cw + pw) / 100) * speed;
            ani(t);
        });
    }

    function counttime() {
        f = setInterval(function() {
            t1 += 10;
        }, 10);
    }
    p.on({
        mouseenter: function() {
            c.stop(false, false);
            clearInterval(f);
            console.log(t1);
        },
        mouseleave: function() {
            ani(t - t1);
            console.log(t1);
        }
    });
    ani(t);
}